package project.utils;

import org.springframework.stereotype.Component;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;


public class GetRandom {
    //使用Java内置的Random类
    public  <T> T javaRandom(List<T> list){
        Random random = new SecureRandom();
        int index = random.nextInt(list.size());
        return list.get(index);
    }
    //使用Java 8的Stream API
    public  <T> T java8Stream(List<T> list){
        Random random = new Random();
        return list.stream()
                .skip(random.nextInt(list.size()))
                .findFirst()
                .orElse(null);
    }

    //多线程ThreadLocalRandom
    public  <T> T threadLocalRandom(List<T> list){
        int randomIndex = ThreadLocalRandom.current().nextInt(list.size());
        return list.get(randomIndex);

    }
    //Fisher-Yates洗牌算法（Knuth洗牌）
    public  <T> T fisherYates(List<T> list){
        SecureRandom secureRandom = new SecureRandom();
        List<T> shuffledOptions = new ArrayList<>(list);
        Collections.shuffle(shuffledOptions, secureRandom);

        return shuffledOptions.get(0);
    }
    //混合熵源增强随机性
    public <T> T generateHybridRandomResult(List<T> options) {
        Random secureRandom = new SecureRandom();

        // 添加本地熵源（如当前纳秒时间）
        long nanoTime = System.nanoTime();
        secureRandom.setSeed(nanoTime); // 重置种子增强熵

        return options.get(secureRandom.nextInt(options.size()));
    }

}
